//
//  WHResetPasswordController.m
//  SquirrelCourier
//
//  Created by 邓伟浩 on 2019/1/3.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHResetPasswordController.h"
#import "WHTextInfoCell.h"
#import "NSString+WH3DES.h" // DES加密

@interface WHResetPasswordController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *loginExChangeTableView;
@property (nonatomic, strong) NSArray *placeHolderArray;

@property (nonatomic, strong) NSMutableArray *useInfoArray;

@property (nonatomic, strong) NSURLSessionDataTask *setLoginPasswordTask;

@end

@implementation WHResetPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"修改密码";
    [self initParams];
    [self setUpTableView];
}

- (void)initParams {
    _placeHolderArray = @[@"请输入原密码", @"请输入新密码(6-12位数字或字母)", @"请再次输入新密码"];
    _useInfoArray = @[@"", @"", @""].mutableCopy;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:dataTableView];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    dataTableView.tableFooterView = [self tableFootView];
    
    [dataTableView registerClass:[WHTextInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHTextInfoCell class])];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorColor = CLineColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    _loginExChangeTableView = dataTableView;
}

- (UIView *)tableFootView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(kRealwidth(32), kRealwidth(20), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    ViewRadius(submitButton, kRealwidth(45)/2);
    [tableFootView addSubview:submitButton];
    NSString *logoutTitle = @"确认";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:logoutTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:attributeStr forState:UIControlStateNormal];
    submitButton.backgroundColor = CMDarkOrangeColor;
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFootView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placeHolderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHTextInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHTextInfoCell class]) forIndexPath:indexPath];
    cell.inputTextField.text = _useInfoArray[indexPath.row];
    cell.inputTextField.secureTextEntry = YES;
    [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
    
    kWeakSelf(self);
    cell.textChangeBlock = ^(NSString *text) {
        [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
    };
    cell.validType = ValideTypePassword;
    cell.inputTextField.keyboardType = UIKeyboardTypeASCIICapable;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

#pragma mark - —————— 事件 ——————

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    NSString *oldPassword = _useInfoArray[0];
    NSString *password = _useInfoArray[1];
    NSString *rePassword = _useInfoArray[2];
    
    if (oldPassword.length == 0 || password.length == 0 || rePassword.length == 0) {
        [WHView showMessage:@"请完善以上信息" inView:self.view];
        return;
    }
    if (![WHValidationHelper validatePassword:password]) {
        [WHView showMessage:@"密码输入不合法!" inView:self.view];
        return;
    }
    if (![password isEqualToString:rePassword]) {
        [WHView showMessage:@"两次输入密码不一致,请重新输入" inView:self.view];
        return;
    }
    
    kWeakSelf(self);
    [self setLoginPassword:_useInfoArray completion:^(id responseObject) {
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            
            if (errCode.intValue == 0) {
                [WHView showMessage:@"设置登录密码成功" inView:nil];
                KPostNotification(KUserInfoChange, nil);
                [weakself.navigationController popViewControllerAnimated:YES];
            } else {
                [WHView showMessage:errorMsg inView:weakself.view];
            }
        }
    }];
}

#pragma mark - —————— 接口 ——————

- (void)setLoginPassword:(NSArray *)userInfoArray completion:(completionBlock)completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_forgetPassWord);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          [NSString encryptUseDES3:userInfoArray[0] key:DES3Key], @"oldPassWord",
                          [NSString encryptUseDES3:userInfoArray[1] key:DES3Key], @"passWord",
                          @"1", @"system",
                          @"2", @"forgetType",
                          nil];
    
    _setLoginPasswordTask = [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        completion(responseObject);
    } failure:^(NSError *error) {
        
    }];
}

- (void)backBtnClicked {
    if (_setLoginPasswordTask) {
        [_setLoginPasswordTask cancel];
        _setLoginPasswordTask = nil;
    }
    [super backBtnClicked];
    
}

@end
